﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Web;
using System.Media;

namespace Goose
{
    public partial class main : Form
    {
        private Thread refleshThread = null;
        private string refleshTxt = null;
        private List<Thread> prosses = new List<Thread>();
        //long k = 3029804000;
        private Thread addReceiveGooseThread = null;
        private Thread addSaleGooseThread = null;
        private Thread addTradeGooseThread = null;
        private Thread setInvalidThread = null;
        private bool uploadbtnState = true;
        private string msg = null;
        private string item = null;
        private ComboBox comboBox = null;

        public main()
        {
            InitializeComponent();            
        }

        /// <summary>
        /// 用户提示信息
        /// </summary>
        /// <param name="msg"></param>
        private void listMsgAdd(String msg) {
            if (listMsg.Items.Count > 10)//只显示10条信息记录
                listMsg.Items.Clear();
            this.listMsg.Items.Add(msg);
            this.listMsg.SelectedIndex = this.listMsg.Items.Count - 1;
        }

        #region 下拉表按键输入取消
        /// <summary>
        /// 下拉列表按键输入取消
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void opcomboBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = true;
        } 
        #endregion




        #region 选择操作
        /// <summary>
        /// 选择操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void opcomboBox_SelectedValueChanged(object sender, EventArgs e)
        {
            ComboBox c = sender as ComboBox;
            //MessageBox.Show((string)c.SelectedItem);
            switch ((string)c.SelectedItem)
            {
                case "鹅苗入场":
                    this.farmidcomboBox.Enabled = true;
                    this.saleInputSetEnable(false);
                    this.uploadbtn.Enabled = true;
                    break;
                case "成品鹅出售":
                    this.farmidcomboBox.Enabled = false;
                    this.saleInputSetEnable(true);
                    this.uploadbtn.Enabled = true;
                    break;
                case "成品鹅回购":
                    this.farmidcomboBox.Enabled = true;
                    this.saleInputSetEnable(true);
                    this.salelabel.Enabled = false;
                    this.retailerIdcombox.Enabled = false;
                    this.uploadbtn.Enabled = true;
                    break;
                case "真伪认证":
                    this.farmidcomboBox.Enabled = false;
                    this.saleInputSetEnable(false);
                    this.uploadbtn.Enabled = false;
                    break;
                case "销号处理":
                    this.farmidcomboBox.Enabled = false;
                    this.saleInputSetEnable(false);
                    this.uploadbtn.Enabled = true;
                    break;
                default: this.farmidcomboBox.Enabled = false;
                    this.saleInputSetEnable(false);
                    this.startbtn.Enabled = false;
                    break;
            }
        } 
        #endregion

       

        #region 初始化
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void main_Load(object sender, EventArgs e)
        {
            PortInit();
            this.farmidcomboBox.SelectedIndex = 0;
            this.opcomboBox.SelectedIndex = 0;
            this.retailerIdcombox.SelectedIndex = 0;
            this.loadList();
        } 
        #endregion


        /// <summary>
        /// 串口初始化
        /// </summary>
        private void PortInit()
        {
            try
            {
                for (int i = 0; i < 4; i++)
                {
                    int ret = API_RF.rf_init(i, 115200);
                    if (ret >= 0)
                    {
                        API_RF.hCom = ret;                        
                        break;
                    }
                }
                if (API_RF.hCom < 0)
                {
                    MessageBox.Show("程序初始化失败，请重启程序！");
                }
            }
            catch (Exception)
            {
                MessageBox.Show("程序初始化失败，请重启程序！");
            }            
        }



        #region 跨线程控件交互委托事件农场、经销商列表控件
        private delegate void delegateclsCombox();
        private void clsCombox()
        {
            farmidcomboBox.Items.Clear();
            farmidcomboBox.Items.Add("请选择");
            farmidcomboBox.SelectedIndex = 0;
            retailerIdcombox.Items.Clear();
            retailerIdcombox.Items.Add("请选择");
            retailerIdcombox.SelectedIndex = 0;
        }

        #endregion

        #region 跨线程控件交互委托事件农场、经销商列表控件
        private delegate void delegateaddCombox();
        private void addCombox()
        {
            comboBox.Items.Add(item);
            comboBox = null;
            item = null;
        }

        #endregion

        /// <summary>
        /// 加载农场和经销商,数据在initInfo文件中
        /// initInfo文件格式为：
        /// 农场
        /// 农场id#农场名
        /// ...
        /// 经销商
        /// 经销商id#经销商名
        /// ...
        /// </summary>
        private void loadList()
        {
            List<String> list = null;
            Op.farmidMap.Clear();
            Op.farmMap.Clear();
            Op.retaileridMap.Clear();
            Op.retailerMap.Clear();

            list = Op.readFile(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.FullyQualifiedName) + "\\initInfo");

                if (list.Count <= 0)
                {
                    MessageBox.Show("数据加载错误！缺少文件initInfo");
                    return;
                }
            

            ////
            int index = list.IndexOf("经销商");
            String[] tmp = new String[2];
            for (int i = 1; i < index; i++)
            {
                tmp = list[i].Split('#');
                
               //农场列表增加
                item = tmp[1];
                comboBox= farmidcomboBox;                
                if (this.InvokeRequired)
                {
                    this.Invoke(new delegateaddCombox(addCombox));
                }
                else
                {
                    addCombox();
                }
                Op.farmidMap.Add(tmp[0],tmp[1]);
                long id=0;
                try
                {
                    id = long.Parse(tmp[0]);
                }
                catch (Exception)
                {


                }
               Op.farmMap.Add(tmp[1],id);
            }
           
            for (int j = index+1; j < list.Count; j++)
            {
                tmp = list[j].Split('#');


               //经销商列表增加
                item = tmp[1];
                comboBox = retailerIdcombox;
                if (this.InvokeRequired)
                {
                    this.Invoke(new delegateaddCombox(addCombox));
                }
                else
                {
                    addCombox();
                }

                Op.retaileridMap.Add(tmp[0], tmp[1]);
                long id = 0;
                try
                {
                    id = long.Parse(tmp[0]);
                }
                catch (Exception)
                {


                }
                Op.retailerMap.Add(tmp[1], id);
            }
            

        }

        /// <summary>
        /// 销售商输入组件禁用/启用
        /// </summary>
        /// <param name="enable"></param>
        private void saleInputSetEnable(Boolean enable)
        {
            this.salelabel.Enabled = enable;
            this.retailerIdcombox.Enabled = enable;
            this.totalweightlabel.Enabled = enable;
            this.totalweighttxt.Enabled = enable;
            this.unitpricelabel.Enabled = enable;
            this.unitpricetxt.Enabled = enable;
            this.totalpricelabel.Enabled = enable;
            this.totalpricetxt.Enabled = enable;
            this.startbtn.Enabled = true;
        }


        //刷新农场/经销商信息

        private void readbtn_Click(object sender, EventArgs e)
        {
            if (this.refleshbtn.Text == "刷新农场/经销商信息")
            {
                this.refleshThread = new Thread(this.reflesh);
                refleshThread.Start();
                refleshThread.IsBackground = true;
                this.prosses.Add(refleshThread);
            }
            
        }

        private void changeTxt()
        {
            this.refleshbtn.Text = this.refleshTxt;
            this.refleshTxt = null;//设空回收垃圾
        }
        private delegate void delegateChangeTxt();

        private void reflesh()
        {
            List<String> list = new List<string>();
            refleshTxt = "正在刷新...";
            if (this.InvokeRequired)
            {
                this.Invoke(new delegateChangeTxt(changeTxt));
            }
            else
            {
                changeTxt();
            }
            try
            {
                
                WebReference.GooseWebServiceImplService gws = new WebReference.GooseWebServiceImplService();                               
                WebReference.farmWs[] fwsList = gws.getFarmList();
                
                list.Add("农场");
                //农场
                foreach (WebReference.farmWs fws in fwsList)
                {
                    list.Add(fws.id + "#" + fws.name);
                }

                WebReference.retailerWs[] rwsList = gws.getRetailerList();

                list.Add("经销商");
               //经销商
                foreach (WebReference.retailerWs rws in rwsList)
                {
                    list.Add(rws.id + "#" + rws.name);                
                }

                //写入文件initInfo
                Op.save<string>(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.FullyQualifiedName) + "\\initInfo", list, false);
            }
            catch (Exception)
            {
                MessageBox.Show("无法连接到服务器，请检查网络!");
            }

            try
            {
                this.refleshTxt = "刷新农场/经销商信息";
                if (this.InvokeRequired)
                    this.Invoke(new delegateChangeTxt(changeTxt));
                else
                    changeTxt();
            }
            catch (Exception)
            {
                //
            }

            loadList();//重新加载到列表


            try
            {
                while (this.refleshThread.IsBackground)
                    this.refleshThread.Abort();                
            }
            catch (Exception)
            {

            }
            
            
        }

        private void unitpricetxt_TextChanged(object sender, EventArgs e)
        {
            TextBox tb = sender as TextBox;
            if (!Op.cheakDouble(tb.Text)&&tb.Text.Length>0)
            {
                tb.Text = tb.Text.Remove(tb.Text.Length-1,1);
                tb.SelectionStart = tb.Text.Length;
            }
            if (this.totalweighttxt.Text != "" && this.unitpricetxt.Text != "")
            {
                this.totalpricetxt.Text = "" + (Double.Parse(this.totalweighttxt.Text) * Double.Parse(this.unitpricetxt.Text));
            }
            else
            {
                this.totalpricetxt.Text = "0";
            }
        }

         //退出系统
        private void main_Closing(object sender, CancelEventArgs e)
        {

            if (MessageBox.Show("是否要退出本系统？","提示",MessageBoxButtons.OKCancel,MessageBoxIcon.Question,MessageBoxDefaultButton.Button2) == DialogResult.Cancel)
            {
                e.Cancel = true;
            }
            else
            {
                for (int i = 0; i < this.prosses.Count; i++)
                {
                    try
                    {
                        this.prosses[i].IsBackground = true;
                    }
                    catch (Exception)
                    {
                        
                    }
                }
                this.Dispose(true);
                this.Close();

            }


        }

        #region 跨线程控件交互委托事件 上传数据按钮
        private delegate void delegateuploadbtnState();
        private void uploadbtnStatechange()
        {
            this.uploadbtn.Enabled = this.uploadbtnState;
            this.startbtn.Enabled = this.uploadbtnState;
            this.uploadreadbtn.Enabled = this.uploadbtnState;
        }
        
        #endregion

        #region 跨线程控件交互委托事件 listMsg消息控件
        private delegate void delegatelistMsgChange();
        private void listMsgChange()
        {
            this.listMsgAdd(this.msg);
            this.openlist.Items.Add(this.msg);
            this.msg = null;
        }


        #endregion


        #region 跨线程控件交互委托事件 countTxt消息控件
        private delegate void delegatecountTxtChange();
        private void countTxtChange()
        {
            this.countTxt.Text="0";
        }


        private void countTxtChangeByThread()
        {
            if (this.InvokeRequired)
                this.Invoke(new delegatecountTxtChange(countTxtChange));
            else
                this.countTxt.Text="0";       
        }

        #endregion


        /// <summary>
        /// 上传鹅苗数据
        /// </summary>
        private void addReceiveGoose()
        {
            //禁用/启用上传数据按钮
            this.uploadbtnState = false;
            if (this.InvokeRequired)
                this.Invoke(new delegateuploadbtnState(uploadbtnStatechange));
            else
                this.uploadbtn.Enabled = this.uploadbtnState;
 
            try
            {
                WebReference.GooseWebServiceImplService gws = new WebReference.GooseWebServiceImplService();
                if (Op.cardIdList.Count > 0)
                    gws.addReceiveGoose(Op.farmId, Op.cardIdList.ToArray(), "");

                //listMsg消息提示
                this.msg="已上传" + Op.cardIdList.Count + "条出售记录！";
                if (this.InvokeRequired)
                    this.Invoke(new delegatelistMsgChange(listMsgChange));
                else
                    this.listMsgAdd(this.msg);

                Op.cardIdList.Clear();//操作数据完成后清除链表数据
                this.countTxtChangeByThread();//计数清零
            }
            catch (Exception)
            {
                MessageBox.Show("无法连接服务器！上传数据失败！");

                //listMsg消息提示
                this.msg = "无法连接服务器！上传数据失败！";
                if (this.InvokeRequired)
                    this.Invoke(new delegatelistMsgChange(listMsgChange));
                else
                    this.listMsgAdd(this.msg);
            }

            //禁用/启用上传数据按钮
            this.uploadbtnState = true;
            if (this.InvokeRequired)
                this.Invoke(new delegateuploadbtnState(uploadbtnStatechange));
            else
                this.uploadbtn.Enabled = this.uploadbtnState; 

            try
            {
                while (this.addReceiveGooseThread.IsBackground)
                {
                    this.addReceiveGooseThread.Abort();
                }
            }
            catch (Exception)
            {
                
                //
            }
        }

        /// <summary>
        /// 上传成品鹅出售
        /// </summary>
        private void addSaleGoose()
        {
            //禁用/启用上传数据按钮
            this.uploadbtnState = false;
            if (this.InvokeRequired)
                this.Invoke(new delegateuploadbtnState(uploadbtnStatechange));
            else
                this.uploadbtn.Enabled = this.uploadbtnState;

            try
            {
                WebReference.GooseWebServiceImplService gws = new WebReference.GooseWebServiceImplService();
                if (Op.cardIdList.Count > 0)
                    gws.addSaleGoose(Op.retailerId, Op.cardIdList.ToArray(), Op.totalWeight, true, Op.unitPrice, true, "");

                
                //listMsg消息提示
                this.msg = "已上传" + Op.cardIdList.Count + "条出售记录！";
                if (this.InvokeRequired)
                    this.Invoke(new delegatelistMsgChange(listMsgChange));
                else
                    this.listMsgAdd(this.msg);

                Op.cardIdList.Clear();
                this.countTxtChangeByThread();//计数清零
            }
            catch (Exception)
            {
                
                MessageBox.Show("无法连接服务器！上传数据失败！");

                //listMsg消息提示
                this.msg = "无法连接服务器！上传数据失败！";
                if (this.InvokeRequired)
                    this.Invoke(new delegatelistMsgChange(listMsgChange));
                else
                    this.listMsgAdd(this.msg);
            }

            //禁用/启用上传数据按钮
            this.uploadbtnState = true;
            if (this.InvokeRequired)
                this.Invoke(new delegateuploadbtnState(uploadbtnStatechange));
            else
                this.uploadbtn.Enabled = this.uploadbtnState;
 
            try
            {
                while (this.addReceiveGooseThread.IsBackground)
                {
                    this.addSaleGooseThread.Abort();
                }
            }
            catch (Exception)
            {
                
               //
            }
        }

        /// <summary>
        /// 上传成品鹅回购
        /// </summary>
        private void addTradeGoose()
        {
            //禁用/启用上传数据按钮
            this.uploadbtnState = false;
            if (this.InvokeRequired)
                this.Invoke(new delegateuploadbtnState(uploadbtnStatechange));
            else
                this.uploadbtn.Enabled = this.uploadbtnState;

            try
            {
                WebReference.GooseWebServiceImplService gws = new WebReference.GooseWebServiceImplService();
                if (Op.cardIdList.Count > 0)
                    gws.addTradeGoose(Op.farmId, Op.cardIdList.ToArray(), Op.totalWeight, true, Op.unitPrice, true, "");

               
                //listMsg消息提示
                this.msg = "已上传" + Op.cardIdList.Count + "条回购记录！";
                if (this.InvokeRequired)
                    this.Invoke(new delegatelistMsgChange(listMsgChange));
                else
                    this.listMsgAdd(this.msg);

                Op.cardIdList.Clear();
                this.countTxtChangeByThread();//计数清零
            }
            catch (Exception)
            {                
                MessageBox.Show("无法连接服务器！上传数据失败！");

                //listMsg消息提示
                this.msg = "无法连接服务器！上传数据失败！";
                if (this.InvokeRequired)
                    this.Invoke(new delegatelistMsgChange(listMsgChange));
                else
                    this.listMsgAdd(this.msg);
            }

            //禁用/启用上传数据按钮
            this.uploadbtnState = true;
            if (this.InvokeRequired)
                this.Invoke(new delegateuploadbtnState(uploadbtnStatechange));
            else
                this.uploadbtn.Enabled = this.uploadbtnState;
 
            try
            {
                while (this.addReceiveGooseThread.IsBackground)
                {
                    this.addTradeGooseThread.Abort();
                }
            }
            catch (Exception)
            {
                
                //线程异常
            }
        }

        /// <summary>
        /// 上传销号处理
        /// </summary>
        private void setInvalid()
        {
            //禁用/启用上传数据按钮
            this.uploadbtnState = false;
            if (this.InvokeRequired)
                this.Invoke(new delegateuploadbtnState(uploadbtnStatechange));
            else
                this.uploadbtn.Enabled = this.uploadbtnState;

            try
            {
                WebReference.GooseWebServiceImplService gws = new WebReference.GooseWebServiceImplService();
                foreach (String cardId in Op.cardIdList)
                {
                    gws.setInvalid(cardId);
                }
               
                //listMsg消息提示
                this.msg = "已在服务器上销号" + Op.cardIdList.Count + "条记录！";
                if (this.InvokeRequired)
                    this.Invoke(new delegatelistMsgChange(listMsgChange));
                else
                    this.listMsgAdd(this.msg);

                Op.cardIdList.Clear();
                this.countTxtChangeByThread();//计数清零
            }
            catch (Exception)
            {
               
                MessageBox.Show("无法连接服务器！上传数据失败！");

                //listMsg消息提示
                this.msg = "无法连接服务器！上传数据失败！";
                if (this.InvokeRequired)
                    this.Invoke(new delegatelistMsgChange(listMsgChange));
                else
                    this.listMsgAdd(this.msg);
            }

            //禁用/启用上传数据按钮
            this.uploadbtnState = true;
            if (this.InvokeRequired)
                this.Invoke(new delegateuploadbtnState(uploadbtnStatechange));
            else
                this.uploadbtn.Enabled = this.uploadbtnState; 

            try
            {
                while (this.addReceiveGooseThread.IsBackground)
                {
                    this.setInvalidThread.Abort();
                }
            }
            catch (Exception)
            {
               //线程异常
            }
        }


        /// <summary>
        /// 上传数据
        /// </summary>
        private void upload() {
            switch (Op.op)
            {
                case "鹅苗入场":
                    this.addReceiveGooseThread = new Thread(this.addReceiveGoose);
                    this.addReceiveGooseThread.Start();
                    this.prosses.Add(this.addReceiveGooseThread);
                    break;
                case "成品鹅出售":
                    this.addSaleGooseThread = new Thread(this.addSaleGoose);
                    this.addSaleGooseThread.Start();
                    this.prosses.Add(this.addSaleGooseThread);
                    break;
                case "成品鹅回购":
                    this.addTradeGooseThread = new Thread(this.addTradeGoose);
                    this.addTradeGooseThread.Start();
                    this.prosses.Add(this.addTradeGooseThread);
                    break;

                case "销号处理":
                    this.setInvalidThread = new Thread(this.setInvalid);
                    this.setInvalidThread.Start();
                    this.prosses.Add(this.setInvalidThread);
                    break;
                default:
                    this.listMsgAdd("无操作！");
                    break;
            }
            
        }


        /// <summary>
        /// 上传按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uploadbtn_Click(object sender, EventArgs e)
        {
            this.tabControl1.SelectedIndex = 1;
            if (MessageBox.Show("是否上传数据？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
            {
                this.getInputData();
                this.upload();
                
            }
            else
            {
                this.listMsgAdd("用户取消上传数据！");
            }
        }


        #region 读卡线程
        /// <summary>
        /// 读卡线程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void startbtn_Click(object sender, EventArgs e)
        {
            if (this.startbtn.Text == "开始")
            {
                this.startbtn.Text = "停止";
                this.readCardIdtimer.Enabled = true;
                this.uploadbtn.Enabled = false;
                this.opcomboBox.Enabled = false;
                this.listMsgAdd("读卡开始！");
                this.readstartbtn.Enabled = false;
                //禁用打开、保存、上传已读数据按钮
                this.openbtn.Enabled = false;
                this.savebtn.Enabled = false;
                this.uploadreadbtn.Enabled = false;
                this.tabControl1.SelectedIndex = 1;//跳到listMsg
            }
            else
            {
                this.startbtn.Text = "开始";
                this.readCardIdtimer.Enabled = false;
                if ((string)opcomboBox.SelectedItem != "真伪认证")
                    this.uploadbtn.Enabled = true;
                this.opcomboBox.Enabled = true;
                this.listMsgAdd("完成读卡！");
                this.readstartbtn.Enabled = true;

                this.openbtn.Enabled = true;
                this.savebtn.Enabled = true;
                this.uploadreadbtn.Enabled = true;
            }
        }
        

        private void checkCardState(byte bytetmp)
        {
            switch (bytetmp)
            {
                case 0x02:
                    this.listMsgAdd("已出售！脚环号 " + Op.cardId);
                    break;
                case 0x00:
                    this.listMsgAdd("已死亡！脚环号 " + Op.cardId);
                    break;
                case 0x01:
                    this.listMsgAdd("已入场。脚环号 " + Op.cardId);
                    break;
                case 0x03:
                    this.listMsgAdd("尚未入场！脚环号 " + Op.cardId);
                    break;
                case 0x04:
                    this.listMsgAdd("已回购，脚环号 "+Op.cardId);
                    break;
                default:
                    this.listMsgAdd("非农友公司产品，谨防假冒！" + Op.cardId);
                    break;

            }
        
        }
       

        private void readCardIdtimer_Tick(object sender, EventArgs e)
        {
           int ret = Op.readByDh();
           byte[] datatmp = null;
           if (ret == 0)//表示寻卡，装载、校验密码成功，为正品
           {
               //读取卡中数据
               datatmp = new byte[] { 0x00 };
               API_RF.rf_read(API_RF.hCom, (byte)(5 * 4 + 0), datatmp);
               switch ((string)this.opcomboBox.SelectedItem)
               {

                   case "鹅苗入场":
                       //检查卡的五区0块信息，若有信息且是数字则为真，声音提示
                       //如果为3，则写入卡的第五区0块信息为1                      
                       if (datatmp[0] == 0x03)//如果脚环是尚未使用
                       {
                           if (!Op.cardIdList.Contains(Op.cardId))
                               this.addCardIdList();//如果链表中没有，则加入链表                           
                           byte[] databyte1 = new byte[] { 0x01 };
                           API_RF.rf_write(API_RF.hCom, (byte)(5 * 4 + 0), databyte1);//标记为1，表示正常使用中
                           System.Media.SystemSounds.Beep.Play();//操作完成,声音提示
                       }
                       else
                           this.checkCardState(datatmp[0]);

                       break;
                   case "成品鹅出售":                       
                      
                       if (datatmp[0] == 0x01)//如果脚环是正常使用
                       {
                           if (!Op.cardIdList.Contains(Op.cardId))
                               this.addCardIdList();//如果链表没有改脚环，则加入链表

                           byte[] databyte2 = new byte[] { 0x02 };
                           API_RF.rf_write(API_RF.hCom, (byte)(5 * 4 + 0), databyte2);//标记2

                           System.Media.SystemSounds.Beep.Play();//操作完成,声音提示
                       }
                       else
                           this.checkCardState(datatmp[0]);

                       break;
                   case "真伪认证":
                       //检查卡的五区0块信息，若有信息且是数字则为真，声音提示
                       switch (datatmp[0])
                       {
                           case 0x02:
                               this.listMsgAdd("农友公司产品，鹅只已出售！脚环号 "+Op.cardId );
                               break;
                           case 0x00:
                               this.listMsgAdd("农友公司产品，鹅只已死亡！脚环号 "+Op.cardId);
                               break;
                           case 0x01:
                               this.listMsgAdd("农友公司产品,鹅只未出售！脚环号 "+ Op.cardId );
                               break;
                           case 0x03:
                               this.listMsgAdd("农友公司产品，尚未使用！脚环号 "+ Op.cardId );
                               break;
                           case 0x04:
                               this.listMsgAdd("农友公司产品，已回购，脚环号 " + Op.cardId);
                               break;
                           default:
                               this.listMsgAdd( "非农友公司产品，谨防假冒！"+Op.cardId );
                               break;

                       }
                       System.Media.SystemSounds.Beep.Play();//操作完成,声音提示

                       break;
                   case "销号处理":
                       //写入卡的第五区0块信息为0
                       if (datatmp[0] != 0x00) //若非死亡状态，则
                       {
                           if (!Op.cardIdList.Contains(Op.cardId))
                               this.addCardIdList();
                           byte[] databyte0 = new byte[] { 0x00 };
                           API_RF.rf_write(API_RF.hCom, (byte)(5 * 4 + 0), databyte0);//标记0
                           System.Media.SystemSounds.Beep.Play();//操作完成,声音提示
                           this.listMsgAdd("销号成功！脚环号 " + Op.cardId);
                       }
                       else
                       {
                           this.listMsgAdd("鹅只已销号！脚环号 " + Op.cardId);
                       }
                       
                       break;
                   case "成品鹅回购":
                      
                       if (datatmp[0] == 0x01)//如果脚环是正常养殖状态使用
                       {
                           if (!Op.cardIdList.Contains(Op.cardId))
                               this.addCardIdList();//如果链表没有改脚环，则加入链表

                           byte[] databyte4 = new byte[] { 0x04 };
                           API_RF.rf_write(API_RF.hCom, (byte)(5 * 4 + 0), databyte4);//标记4,表示回购成功

                           System.Media.SystemSounds.Beep.Play();//操作完成,声音提示
                       }
                       else
                           this.checkCardState(datatmp[0]);
                       
                       break;
                   default:
                       break;
               }
           }
           else//未备案
           {
               uint s = 0;
               try
               {
                   API_RF.rf_card(API_RF.hCom, (byte)0, ref s);
               }
               catch (Exception)
               {

               }
               if (API_RF.snr != 0)
                   listMsgAdd( "尚未备案！脚环号 "+API_RF.snr);
           }

           try
           {
               API_RF.rf_halt(API_RF.hCom);//停止对卡操作
           }
           catch (Exception)
           {
               listMsgAdd("读卡异常！");//缺失dll文件异常01
           }
        }

        #endregion



        private void addCardIdList()
        {           
            listMsgAdd("已读入！脚环号 "+Op.cardId);//写到信息里去
            Op.cardIdList.Add(Op.cardId);//加入链表

            try
            {
                this.countTxt.Text = "" + (int.Parse(this.countTxt.Text) + 1);//计数
            }
            catch (Exception)
            {

                //
            }

        }

        private void clearbtn_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("是否清空已读入的脚环信息数据？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
            {
                Op.cardIdList.Clear();
                listMsg.Items.Clear();
                this.countTxt.Text = "0";
                listMsgAdd("已清空已读入的脚环信息数据！");
                tabControl1.SelectedIndex = 1;
            }

        }


        /// <summary>
        /// 读取信息按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void readstartbtn_Click(object sender, EventArgs e)
        {           
            if (this.readstartbtn.Text == "开始")
            {
                this.readstartbtn.Text = "停止";
                this.readTimer.Enabled = true;
                this.startbtn.Enabled = false;
                this.uploadbtn.Enabled = false;

                //禁用打开、保存、上传已读数据按钮
                this.openbtn.Enabled = false;
                this.savebtn.Enabled = false;
                this.uploadreadbtn.Enabled = false;
            }
            else
            {
                this.readstartbtn.Text = "开始";
                this.readTimer.Enabled = false;
                this.startbtn.Enabled = true;
                if ((string)opcomboBox.SelectedItem != "真伪认证")
                {
                    this.uploadbtn.Enabled = true;
                }

                this.openbtn.Enabled = true;
                this.savebtn.Enabled = true;
                this.uploadreadbtn.Enabled = true;
            }
        }

        /// <summary>
        /// 读取信息timer
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void readTimer_Tick(object sender, EventArgs e)
        {
            
            int ret=Op.readByDh();

            //cardid = this.k+"";
            //this.k++;
            //this.countTxt.Text = cardid;

            try
            {
                API_RF.rf_halt(API_RF.hCom);//停止对卡操作
            }
            catch (Exception)
            {                
                this.listdata.Items.Add("读卡异常");//缺失dll文件异常01
                this.listdata.SelectedIndex = this.listdata.Items.Count - 1;
            }
            if (ret == 0)//为正品
            {
                try
                {
                    WebReference.GooseWebServiceImplService gws = new Goose.WebReference.GooseWebServiceImplService();
                    WebReference.receiveGooseWs rgws = gws.getReceiveInfo(Op.cardId);
                    if (rgws != null)
                    {
                        listdata.Items.Clear();
                        listdata.Items.Add("场主:" + rgws.farmerName);
                        listdata.Items.Add("农场:" + rgws.farmName);
                        listdata.Items.Add("批次时间:" + rgws.receiveDate);
                        listdata.Items.Add("电话:" + rgws.phone);
                    }
                }
                catch (Exception)
                {
                    MessageBox.Show("无法连接到服务器！");
                }
            }
            else//校验密码失败
            {                
                if(API_RF.snr!=0)
                    listdata.Items.Add( "尚未备案！脚环号 "+API_RF.snr );
            }
        }

        private void openbtn_Click(object sender, EventArgs e)
        {
            
            if (this.openFileDialog.ShowDialog() == DialogResult.OK)
            {
                String filePath = this.openFileDialog.FileName;
                List<string> l = Op.readFile(filePath);
                string farmName=null;
                string retailerName = null;
                Op.cardIdList.Clear();
                openlist.Items.Clear();

                foreach (string s in l) {
                    Op.cardIdList.Add(s);
                }
                
                openlist.Items.Add("操作："+Op.cardIdList[0]);
                Op.op = Op.cardIdList[0];
                switch (Op.cardIdList[0])
                {
                    case "鹅苗入场":
                        if (Op.cardIdList[1] != "undefine")
                        {
                            Op.farmidMap.TryGetValue(Op.cardIdList[1], out farmName);
                        }
                        else
                        {
                            farmName = "未定义";
                        }
                        openlist.Items.Add("农场：" + farmName);
                        Op.cardIdList.RemoveAt(1);
                        break;
                    case "成品鹅出售":
                        if (Op.cardIdList[1] != "undefine")
                        {
                            Op.retaileridMap.TryGetValue(Op.cardIdList[1], out retailerName);
                        }
                        else
                        {
                            retailerName = "未定义";
                        }
                        openlist.Items.Add("经销商：" + retailerName);
                        openlist.Items.Add("单价：" + Op.cardIdList[2] + "元");
                        openlist.Items.Add("总重：" + Op.cardIdList[3] + "千克");
                        Op.cardIdList.RemoveAt(3);
                        Op.cardIdList.RemoveAt(2);
                        Op.cardIdList.RemoveAt(1);
                        break;
                    case "成品鹅回购":
                        if (Op.cardIdList[1] != "undefine")
                        {
                            Op.farmidMap.TryGetValue(Op.cardIdList[1], out farmName);
                        }
                        else
                        {
                            farmName = "未定义";
                        }
                        openlist.Items.Add("农场：" + farmName);
                        openlist.Items.Add("单价：" + Op.cardIdList[2]+"元");
                        openlist.Items.Add("总重：" + Op.cardIdList[3]+"千克");
                        Op.cardIdList.RemoveAt(3);
                        Op.cardIdList.RemoveAt(2);
                        Op.cardIdList.RemoveAt(1);
                        break;
                    default:
                        break;

                }                
                Op.cardIdList.RemoveAt(0);
                openlist.Items.Add("一共有"+Op.cardIdList.Count+"个脚环ID");

                foreach (string s in Op.cardIdList)
                {
                    openlist.Items.Add(s);
                }
                
            }
        }


        /// <summary>
        /// 获取输入数据，数据存放到Op类里
        /// </summary>
        private void getInputData() {
            String farm = (String)farmidcomboBox.SelectedItem;
            String retailer = (String)retailerIdcombox.SelectedItem;
            Op.farmMap.TryGetValue(farm, out Op.farmId);
            Op.retailerMap.TryGetValue(retailer, out Op.retailerId);
            Op.totalWeight = 0;//总重初始化
            Op.unitPrice = 0;//单价初始化
            if (this.totalweighttxt.Text != "")
            {
                Op.totalWeight = Double.Parse(this.totalweighttxt.Text);//获取总重
            }
            if (this.unitpricetxt.Text != "")
            {
                Op.unitPrice = Double.Parse(this.unitpricetxt.Text);//获取单价
            }

            Op.op = this.opcomboBox.SelectedItem.ToString();
        }

        private void savebtn_Click(object sender, EventArgs e)
        {

            this.getInputData();
            List<string> l = new List<string>();
            l.Add(this.opcomboBox.SelectedItem.ToString());
            switch ((string)this.opcomboBox.SelectedItem) {
                case "鹅苗入场":                     
                    if (Op.farmId != 0)
                    {
                        l.Add(Op.farmId + "");
                    }
                    else {
                        l.Add("undefine");
                    }                    
                    break;
                case "成品鹅出售":                   
                    if (Op.retailerId != 0)
                    {
                        l.Add(Op.retailerId + "");
                    }
                    else
                    {
                        l.Add("undefine");
                    }
                    l.Add(""+Op.unitPrice);
                    l.Add(""+Op.totalWeight);
                    break;
                case "成品鹅回购":                    
                    if (Op.farmId != 0)
                    {
                        l.Add(Op.farmId + "");
                    }
                    else
                    {
                        l.Add("undefine");
                    }
                    l.Add("" + Op.unitPrice);
                    l.Add("" + Op.totalWeight);
                    break;
                default:
                    break;
            
            }

            foreach (string s in Op.cardIdList)
            {
                l.Add(s);
            }

            DateTime curtime = System.DateTime.Now;
            this.saveFileDialog.FileName = curtime.Year + "年" + curtime.Month + "月" + curtime.Day + "日" + curtime.Hour + "点" + curtime.Minute + "分" + opcomboBox.SelectedItem.ToString();
            
            if (this.saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                if (Op.save(this.saveFileDialog.FileName + ".goo", l, false))
                {
                    this.openlist.Items.Clear();
                    this.openlist.Items.Add(this.saveFileDialog.FileName + "存储成功！");
                    this.openlist.SelectedIndex = this.openlist.Items.Count - 1;
                    Op.cardIdList.Clear();
                }
                else
                {
                    this.openlist.Items.Clear();
                    this.openlist.Items.Add(this.saveFileDialog.FileName + "存储失败！请尝试再次存储！");
                    this.openlist.SelectedIndex = this.openlist.Items.Count - 1;
                }
            }   
        }

        private void resetcountbtn_Click(object sender, EventArgs e)
        {
            this.countTxt.Text = "0";
        }

        private void uploadreadbtn_Click(object sender, EventArgs e)
        {
            this.tabControl1.SelectedIndex = 1;
            if (MessageBox.Show("是否上传打开的数据？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
            {
                
                this.upload();
            }
            else
            {
                listMsgAdd("用户取消上传打开的数据！");
            }
        }

    }
}